import ecs100.UI;

import java.util.*;

public class Pencil_2 {
    private double lastX;
    private double lastY;

    class Point {
        private double x;
        private double y;

        public Point(double x, double y) {
            this.x = x;
            this.y = y;
        }
    }

    Stack<List<Point>> undoStack = new Stack<>();
    List<Point> temp;

    /**
     * Respond to mouse events
     */
    public void doMouse(String action, double x, double y) {
        if (action.equals("pressed")){
            temp = new ArrayList<>();
            lastX = x;
            lastY = y;
            temp.add(new Point(x, y));
        }
        else if (action.equals("dragged")){
            UI.drawLine(lastX, lastY, x, y);
            lastX = x;
            lastY = y;
            temp.add(new Point(x, y));
        }
        else if (action.equals("released")){
            UI.drawLine(lastX, lastY, x, y);
            temp.add(new Point(x, y));
            undoStack.push(new ArrayList<>(temp));
            temp.clear();
        }

    }

    public void setupGUI(){
        UI.setMouseMotionListener(this::doMouse);
        UI.addButton("Quit", UI::quit);
        UI.addButton("Undo", ()->{
            if (undoStack.isEmpty()) {
                return;
            }

            List<Point> undoPoints = undoStack.pop();
            for (int i = 0; i < undoPoints.size() - 1; i++) {
                Point point1 = undoPoints.get(i);
                Point point2 = undoPoints.get(i + 1);

                UI.eraseLine(point1.x, point1.y, point2.x, point2.y);
            }

        });
        UI.setLineWidth(3);
        UI.setDivider(0.0);
    }

    public static void main(String[] arguments){
        new Pencil_2().setupGUI();
    }

}
